package com.lancoo.lancooknowledgecourseware;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.tu.loadingdialog.LoadingDailog;
import com.lancoo.cpbase.authentication.base.AddressOperater;
import com.lancoo.cpbase.authentication.base.ExitBack;
import com.lancoo.cpbase.authentication.base.LoginBack;
import com.lancoo.cpbase.authentication.base.LoginOperate;
import com.lancoo.klgcourseware.api.KlgEnglishApi;
import com.lancoo.klgcourseware.entity.KlgApiResponse;
import com.lancoo.klgcourseware.entity.ResourcePlatFormConfigure;
import com.lancoo.klgcourseware.entity.bean.KlgDbConstant;
import com.lancoo.lancooknowledgecourseware.entity.CloudPlatformConfigModel;

import java.util.concurrent.TimeUnit;

import io.reactivex.Single;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import lancoo.com.net.retrofitrxjava.NetworkTransformer;
import lancoo.com.net.retrofitrxjava.RxApiManager;
import lancoo.com.net.retrofitrxjava.network.Network;
import lancoo.com.net.retrofitrxjava.subscriber.NormalSubscriber;

/**
 * Created by pengmi on 2019/6/12.
 * Description:
 */
public class SplashActivity extends AppCompatActivity implements View.OnClickListener{

    private final int USER_STATUS_VALID = 1;
    private final int USER_STATUS_INVALID = -1;

    private static final String ALERT_PROTECT_SELF="private_protect_self2";

    protected LoginOperate mOperate;
    private CompositeDisposable mCompositeDisposable;
    private TextView tv_address;

    public static void launch(Context mContext) {
        Intent mIntent = new Intent(mContext, SplashActivity.class);
//        mIntent.putExtra("Data","FreeStudyV2");
        mContext.startActivity(mIntent);

    }
    public static void launch(Context mContext, String data) {
        Intent mIntent = new Intent(mContext, SplashActivity.class);
        mIntent.putExtra("Data",data);
        mContext.startActivity(mIntent);

    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);//隐藏状态栏
        tv_address = findViewById(R.id.tv_address);
        tv_address.setText(""+ MainActivity.BASE_URL);
        mCompositeDisposable = new CompositeDisposable();
        if (!this.isTaskRoot()) {
            Intent mainIntent = getIntent();
            String action = mainIntent.getAction();
            if (mainIntent.hasCategory(Intent.CATEGORY_LAUNCHER) && Intent.ACTION_MAIN.equals(action)) {
                finish();
                Log.e("aaaa","是在这儿销毁的1");
                return;
            }
        }

        //沉浸式
        mOperate = new LoginOperate(this);
        reLogin();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mCompositeDisposable.clear();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        finish();
        Log.e("aaaa","是在这儿销毁的2");
    }

    private void reLogin() {
        mCompositeDisposable.add(
                Single.fromCallable(()->mOperate.getCurrentUserState())
                        .timeout(15, TimeUnit.SECONDS)
                        .onErrorReturnItem(USER_STATUS_INVALID)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(this::onUserStateFetch)
        );
    }

    private void onUserStateFetch(int UserStatus){
        Log.e("aaaa","去登陆。。。"+UserStatus);
        if (UserStatus == USER_STATUS_VALID) {
            Log.e("aaaa", "进来了......");
            AddressOperater addressOperater = new AddressOperater(this);
            getKlgUrl(addressOperater.getBaseAddress());
        } else {
            mOperate.goToLoginActivity(this, new LoginBack() {
                @Override
                public void loginSuccess() {
                    reLogin();
                }
            }, new ExitBack() {
                @Override
                public void exit() {
                    finish();
                    Log.e("aaaa","是在这儿销毁的3");
                }
            });
            overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
//            finish();
            Log.e("aaaa","是在这儿销毁的4");
        }
    }

    private void initView(){
        findViewById(R.id.btn_enter).setOnClickListener(this);
        findViewById(R.id.btn_exit).setOnClickListener(this);
        findViewById(R.id.btn_edit).setOnClickListener(this);
    }

    private void getKlgUrl(String url){
        Disposable disposable = Network.getXmlData(api.class, url).getSystemServer("A00")
                .compose(NetworkTransformer.<CloudPlatformConfigModel>commonSchedulers())
                .subscribeWith(new NormalSubscriber<CloudPlatformConfigModel>() {

                    @Override
                    public void onNext(CloudPlatformConfigModel cloudPlatformConfigModel) {
                        super.onNext(cloudPlatformConfigModel);
                        if (cloudPlatformConfigModel.getSystemServerMsgModels() != null && cloudPlatformConfigModel.getSystemServerMsgModels().size() > 0) {
                            for (CloudPlatformConfigModel.SystemServerMsgModel systemServerMsgModel : cloudPlatformConfigModel.getSystemServerMsgModels()) {
                                // 知识点
                                if(TextUtils.equals("A00",systemServerMsgModel.getSysID())){
                                    KlgDbConstant.klg_baseUrl=systemServerMsgModel.getWsSvrAddr();
                                    MainActivity.BASE_URL= KlgDbConstant.klg_baseUrl;
                                    tv_address.setText(""+ MainActivity.BASE_URL);
                                    //获取知识点多媒体资料ip+port
//                                    getKlgConfig();
                                }
                            }
                        } else {
                        }
                        Log.e("aaaa","获取知识点课件配置成功");
                        initView();

                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        Log.e("aaaaa", "onError." + e.toString());
                    }
                });
        RxApiManager.getInstance().add(disposable);
    }


    @Override
    public void onClick(View v) {
        int id=v.getId();
        if(id==R.id.btn_exit){
            mOperate.logOut();
            mOperate.goToLoginActivity(this, new LoginBack() {
                @Override
                public void loginSuccess() {
                    reLogin();
                }
            }, new ExitBack() {
                @Override
                public void exit() {
                    finish();
                    Log.e("aaaa","是在这儿销毁的5");
                }
            });
            overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
//            finish();
            Log.e("aaaa","是在这儿销毁的6");
        }else if(id==R.id.btn_enter){
          MainActivity.launch(this);
        }else if(id==R.id.btn_edit){
            showDialog();
        }
    }

    private void showDialog(){
        View inflate = LayoutInflater.from(this).inflate(R.layout.dialog_edit_address, null);
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setCancelable(false);
        builder.setView(inflate);
        builder.setTitle("修改知识点课件访问地址");
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        final EditText editText = inflate.findViewById(R.id.edit_txt);
        builder.setPositiveButton("修改", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                changeAddress(editText.getText().toString().trim());
            }
        });
        AlertDialog alertDialog = builder.create();
        alertDialog.show();

        editText.setText(tv_address.getText());
        editText.setSelection(editText.getText().length());
    }

    protected void changeAddress(final String address){
        if(TextUtils.isEmpty(address)){
            return;
        }
        if(TextUtils.equals(address,tv_address.getText())){
            return;
        }
        String end="";
        if(!address.endsWith("/")){
            end="/";
        }
        LoadingDailog.Builder builder=new LoadingDailog.Builder(this);
        builder.setCancelable(false);
        builder.setShowMessage(false);
        final LoadingDailog loadingDailog = builder.create();
        loadingDailog.show();
        Network.getJsonData(KlgEnglishApi.class, address+end).getPlatFormConfigure()
                .compose(NetworkTransformer.commonSchedulers())
                .subscribe(new NormalSubscriber<KlgApiResponse<ResourcePlatFormConfigure>>(){
                    @Override
                    public void onNext(KlgApiResponse<ResourcePlatFormConfigure> resourcePlatFormConfigureKlgApiResponse) {
                        super.onNext(resourcePlatFormConfigureKlgApiResponse);
                        Toast.makeText(SplashActivity.this,"修改成功",Toast.LENGTH_SHORT).show();
                        KlgDbConstant.klg_baseUrl=address+(address.endsWith("/")?"":"/");
                        MainActivity.BASE_URL= KlgDbConstant.klg_baseUrl;
                        tv_address.setText(""+ MainActivity.BASE_URL);
                        loadingDailog.dismiss();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        Toast.makeText(SplashActivity.this,"修改失败",Toast.LENGTH_SHORT).show();
                        loadingDailog.dismiss();
                    }
                });
    }

}
